package com.itheima.reggie.filter;

import com.alibaba.fastjson.JSON;
import com.itheima.reggie.common.BaseContext;
import com.itheima.reggie.common.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.AntPathMatcher;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author DL5O
 * @version 1.0
 * 登陆过滤器，检查用户是否登陆
 */
@WebFilter(filterName = "loginCheckFilter", urlPatterns = "/*")
@Slf4j
public class LoginCheckFilter implements Filter {
    //路径匹配器，支持通配符的写法
    public static final AntPathMatcher PATH_MATCHER = new AntPathMatcher();

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        HttpServletRequest request = (HttpServletRequest) servletRequest;
        HttpServletResponse response = (HttpServletResponse) servletResponse;

        //1.获取本次操作的uri
        String requestURI = request.getRequestURI();

        //定义不需要处理的请求处理路径
        String[] urls = new String[]{
                "/employee/login",
                "/employee/logout",
                //如果想要通过通配符的方式进行匹配需要使用工具类
                "/backend/**",
                "/front/**",
                "/common/**",
                "/user/login",//移动端发送短信
                "/user/sendMsg",//移动端登陆
                "/doc.html",
                "/webjars/**",
                "/swagger-resources",
                "/v2/api-docs"
        };

        //2.判断本次请求是否需要处理
        boolean flag = check(urls, requestURI);

        //3.如果不需要处理，那么直接放行即可
        if (flag) {
            //log.info("本次请求{}不需要处理");
            filterChain.doFilter(request, response); //放行
            return;
        }

        //4-1.判断登陆状态(PC端，管理端)，如果已经登陆，则直接放行
        if (request.getSession().getAttribute("employee") != null) {
            //log.info("用户已登陆，用户id为:{}", request.getSession().getAttribute("employee"));
            //获取session域中的id，并把该id存入到线程中去，作为独立的局部变量
            Long empId = (Long) request.getSession().getAttribute("employee");
            BaseContext.setCurrentId(empId);
            filterChain.doFilter(request, response);
            return;
        }

        //4-2.判断登陆状态(移动端，用户端)，如果已经登陆，则直接放行
        if (request.getSession().getAttribute("user") != null) {
            log.info("用户已登陆，用户id为:{}", request.getSession().getAttribute("user"));

            Long userId = (Long) request.getSession().getAttribute("user");
            BaseContext.setCurrentId(userId);

            filterChain.doFilter(request, response);
            return;
        }

        //5.如果没有登陆则返回未登陆结果，通过输出流的方式向客户端页面响应数据
        response.getWriter().write(JSON.toJSONString(R.error("NOTLOGIN")));
        //log.info("用户未登陆");
        return;
    }

    /**
     * 路径匹配，检查本次请求是否需要放行
     * @param urls
     * @param requestUrl
     * @return
     */
    public boolean check(String[] urls, String requestUrl) {
        boolean flag = false;
        for (String url : urls) {
            flag = PATH_MATCHER.match(url, requestUrl);
            if (flag) {
                break;
            }
        }
        return flag;
    }

}
